/*
 *
 *  Created on: 2020��1��1��
 *      Author: Administrator
 */


#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "../../include/queue/linked_queue.h"
#include "../../include/common.h"


void init_queue(LinkedQueue* queue) {

	if (queue == NULL) {
		printf("queue is null!");
		return;
	}

	queue->front = (Node*)malloc(sizeof(Node));
	queue->front->next = NULL;
	if (queue->front == NULL) {
		printf("init queue fail!");
		return;
	}
	queue->rear = queue->front;
}

void create_queue(LinkedQueue* queue, int array[], int length) {

	if (!is_queue_empty(queue)) {
		printf("queue is not empty!");
		return;
	}

	for (int i = 0; i < length; ++i) {
		enqueue(queue, array[i]);
	}
}

bool is_queue_empty(LinkedQueue* queue) {

	if (queue->front->next == NULL) {
		return true;
	}
	return false;
}

bool enqueue(LinkedQueue* queue, int value) {

	// 创建新节点
	Node* node = (Node*)malloc(sizeof(Node));
	if (node == NULL) {
		printf("mem queue node alloc error!");
		return false;
	}
	node->value = value;
	node->next = NULL;

	// 尾插法
	queue->rear->next = node;
	queue->rear = node;

	return true;
}

int dequeue(LinkedQueue* queue) {

	if (is_queue_empty(queue)) {
		return ERROR;
	}

	Node* temp = queue->front->next;
	int result = temp->value;

	// 头删法
	queue->front->next = temp->next;
	// bug 如果队列只有一个结点
	if (temp->next == NULL)
		queue->rear = queue->front; // 删除后同时指向头结点
	free(temp);

	return result;
}

void print_queue(LinkedQueue* queue) {

	Node* p = queue->front->next;

	while (p != NULL) {
		printf("%d ", p->value);
		p = p->next;
	}
	printf("\n");
}

